<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="tag" tagdir="/WEB-INF/tags"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>layuiTitle</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<!-- 为兼容火狐此引用必须放在这里 -->
		<tag:header headerType="base"/>
	</head>
	<body>
		<div class="compre-search">
		 	<div class="layui-btn-group layui-btn-left compreTable">
		    	<button class="layui-btn layui-btn-primary" data-type="add"><i class="layui-icon"></i>添加</button>
		    	<button class="layui-btn layui-btn-primary" data-type="batchDel"><i class="layui-icon">&#xe640;</i>批量删除</button>
		    	<button class="layui-btn layui-btn-primary" data-type="flushAll"><i class="layui-icon">&#xe639;</i>FlushAll</button>
		    	<button class="layui-btn layui-btn-primary" data-type="flushDb"><i class="layui-icon">&#xe640;</i>FlushDb</button>
		  	</div>
		  	<div class="layui-right-search">
		  		<form class="layui-form layui-form-left" action="">
				    <select name="dbConfId" id="dbConfId" lay-search="" lay-filter="dbConfId">
				    </select>
			    </form>
			    <form class="layui-form layui-form-left" action="">
				    <select name="dbId" id="dbId" lay-search="" lay-filter="dbId">
				    </select>
			    </form>
		  		<input type="text" name="" id="cacheKey" required lay-verify="required" placeholder="根据缓存key搜索" autocomplete="off" class="layui-input layui-input-right">  
		  		<button class="layui-btn layui-btn-primary layui-btn-left" id="searchTable"><i class="layui-icon">&#xe615;</i>搜索</button>
		  	</div> 
	  	</div>
		<table class="layui-table" lay-data="{height: 'full-120', cellMinWidth: 50, limit:15}" lay-filter="compreTable">
	  	<thead>
		    <tr>
		      	<th lay-data="{type:'checkbox', fixed: 'left'}"></th>
				<th lay-data="{field:'key'}">key</th>
				<th lay-data="{field:'type'}">type</th>
				<th lay-data="{field:'value'}">value</th>
		      	<th lay-data="{fixed: 'right', width:178, align:'center', toolbar: '#barTable'}">操作</th>
		    </tr>
	  </thead>
	</table>
	
	<!-- 操作绑定 -->
	<script type="text/html" id="barTable">
		<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
	</script>
	               
	<script>
		layui.use(['table','form'], function(){
			var table = layui.table,
				form = layui.form,
		  		$ = layui.$;
			//异步加载db配置
			$.ajax({
				url: '${basePath}redis/getAsyncRedisConf',
				dataType: 'json',
				type: "post",
				data: {},
				async: false,
				success: function(result){
					if(result){
						var confHtml = new Array();
						for(var i=0; i< result.length; i++){
							var conf = result[i];
							confHtml.push("<option value='"+conf['id']+"'>" + conf['dbDesc'] + "</option>");
						}
						$('#dbConfId').html(confHtml.join(""));
						//渲染下拉框
						form.render('select');
						renderDb($('#dbConfId').find('option:selected').val());
					}
				},
				error: function(){
					top.layer.msg('系统异常,请联系管理员');
				}
			});
			//联动渲染redis库
			function renderDb(dbId){
				$.ajax({
					url: '${basePath}redis/getAsyncDbForRedis?',
					dataType: 'json',
					type: "post",
					data: {dbId: dbId},
					async: false,
					success: function(result){
						if(result){
							var confHtml = new Array();
							for(var i=0; i< result.length; i++){
								var conf = result[i];
								confHtml.push("<option value='"+conf['id']+"'>" + conf['name'] + "</option>");
							}
							$('#dbId').html(confHtml.join(""));
							//渲染下拉框
							form.render('select');
						}
					},
					error: function(){
						top.layer.msg('系统异常,请联系管理员');
					}
				});
			}
		  	var tableOptions = {
		        url: '${basePath}redis/pageCache', //请求地址
		        method: 'POST', //方式
		        id: 'listReload', //生成 Layui table 的标识 id，必须提供，用于后文刷新操作，笔者该处出过问题
		        page: true, //是否分页
		        where: { 
		        	type: "all" , 
		        	dbId: $('#dbConfId').find('option:selected').val(),
		        	dbIndex: $('#dbId').find('option:selected').val(),
		        	cacheKey: 'nokey'
		        	}, //请求后端接口的条件，该处就是条件错误点，按照官方给出的代码示例，原先写成了 where: { key : { type: "all" } }，结果并不是我想的那样，如此写，key 将是后端的一个类作为参数，里面有 type 属性，如果误以为 key 是 Layui 提供的格式，那就大错特错了
		        response: { //定义后端 json 格式，详细参见官方文档
		            statusName: 'code', //状态字段名称
		            statusCode: '200', //状态字段成功值
		            msgName: 'msg', //消息字段
		        }
		    };
		    table.init('compreTable', tableOptions);
		  	//条件搜索	
		  	$('#searchTable').on('click',function(){
		  		table.reload("listReload", {
		             where: {
		            	 //条件放置
		            	 dbId: $('#dbConfId').find('option:selected').val(),
		            	 dbIndex: $('#dbId').find('option:selected').val(),
		            	 cacheKey: $('#cacheKey').val()
		             },
		             page:{
			        		curr: 1
			         }
		        });
		  	});
		  	//监听表格复选框选择
		  	table.on('checkbox(compreTable)', function(obj){
		    	console.log(obj)
		  	});
		  	//监听下拉列表change事件
		  	form.on('select(dbConfId)', function(data){
		  		table.reload("listReload", {
		             where: {
		                     dbId: data.value
		             },
		             page:{
		        		curr: 1
		        	}
		        });
		  	});
		    //监听下拉列表change事件
		  	form.on('select(dbId)', function(data){
		  		table.reload("listReload", {
		             where: {
		                     dbIndex: data.value
		             },
		             page:{
		        		curr: 1
		        	}
		        });
		  	});
		  	//监听工具条
		  	table.on('tool(compreTable)', function(obj){
			    var data = obj.data;
			    var dbId = $('#dbConfId').find('option:selected').val(),
        	 		dbIndex = $('#dbId').find('option:selected').val();
			    if(obj.event === 'del'){
				    top.layer.confirm('确定删除?', function(index){
				      	$.post('${basePath}redis/deleteKeys',{dbId: dbId, dbIndex: dbIndex, keys: data.key},function(result){
				      		top.layer.msg(result.msg);
				      		table.reload('listReload');
				        	top.layer.close(index);
				      	});
				    });
			    } else if(obj.event === 'edit'){
			      	window.top.$.layerFrame({callBack:function(){table.reload('listReload');},content: ['${basePath}redis/toCacheUpdate?dbId=' + dbId + '&dbIndex=' + dbIndex + '&key=' + data.key,'no'],title: '修改',});
			    }
		  	});
		  	
		  	//操作按钮事件绑定
		  	var $ = layui.$, active = {
	  			add: function(opt){
	  				var dbId = $('#dbConfId').find('option:selected').val(),
	            	 	dbIndex = $('#dbId').find('option:selected').val();
			  		window.top.$.layerFrame({callBack:function(){table.reload('listReload');},content: ['${basePath}redis/toCacheAdd?dbId=' + dbId + '&dbIndex=' + dbIndex,'no'],title: '添加',});
			  	},
			  	batchDel: function(opt){
			  		var checkStatus = table.checkStatus('listReload'),data = checkStatus.data,keys= new Array();
			  		if(data.length == 0){
			  			top.layer.msg("至少选择一条记录");
			  			return;
			  		}
			  		for(var i=0; i< data.length; i++){
			  			keys.push(data[i]['key']);
			  		}
			  		var dbId = $('#dbConfId').find('option:selected').val(),
            	 	dbIndex = $('#dbId').find('option:selected').val();
			  		top.layer.confirm('确定清理所选择缓存数据【ps:如果缓存中存放了重要数据请谨慎操作】?', function(index){
				      	$.post('${basePath}redis/deleteKeys',{dbId: dbId, dbIndex: dbIndex, keys: keys.join(',')},function(result){
				      		top.layer.msg(result.msg);
				      	});
				      	table.reload('listReload');
			        	top.layer.closeAll();
				    });
			  	},
			  	flushAll: function(opt){
			  		//top.layer.msg('由于本项目DB1存放了shiro session信息, 禁止清除所有缓存');
			  		//return;
			  		var dbId = $('#dbConfId').find('option:selected').val();
			  		top.layer.confirm('确定清理所有缓存数据【ps:如果缓存中存放了重要数据请谨慎操作】?', function(index){
				      	$.post('${basePath}redis/flushAll',{dbId: dbId},function(result){
				      		top.layer.msg(result.msg);
				      	});
				      	table.reload('listReload');
			        	top.layer.closeAll();
				    });
			  	},
			  	flushDb: function(opt){
			  		var dbId = $('#dbConfId').find('option:selected').val(),
            	 	dbIndex = $('#dbId').find('option:selected').val();
// 			  		if(dbIndex == 1){
// 			  			top.layer.msg('由于本项目存放了shiro session信息, 无法清除DB1缓存');
// 			  			return;
// 			  		}
			  		top.layer.confirm('确定清理指定库缓存数据【ps:如果缓存中存放了重要数据请谨慎操作】?', function(index){
				      	$.post('${basePath}redis/flushDb',{dbId: dbId, dbIndex: dbIndex},function(result){
				      		top.layer.msg(result.msg);
				      	});
				      	table.reload('listReload');
			        	top.layer.close(index);
				    });
			  	}
			};
		  
		  	$('.compreTable .layui-btn').on('click', function(){
		    	var type = $(this).data('type');
		    	active[type] ? active[type].call(this) : '';
		  	});
		});
	</script>
	</body>
</html>